<script setup lang="ts">
import api from '@/api'
import { useUserStore } from '@/store'

const props = defineProps<{
  classInfo: (Awaited<ReturnType<typeof api.classes.getClassInfoByClassId>>['data']
    & Awaited<ReturnType<typeof api.classes.getClassesByCurrentUser>>['data'][number])
}>()

const userStore = useUserStore()

const data = reactive<{
  memberInfos: Awaited<ReturnType<typeof api.classes.getMembersByClassId>>['data']
}>({
  memberInfos: [],
})

const avatarLoadErrorMap = reactive<Map<string, boolean>>(new Map())

function handleAvatarError(userId: string) {
  console.error(`Avatar for user ${userId} failed to load.`)
  avatarLoadErrorMap.set(userId, true)
}

watch(() => props.classInfo, async ({ id }) => {
  try {
    const resp = await api.classes.getMembersByClassId(id)
    if (resp.code === 0) {
      data.memberInfos = resp.data.map((member) => {
        if (!member.avatar) {
          avatarLoadErrorMap.set(`${member.userId}`, true)
        }
        else {
          avatarLoadErrorMap.set(`${member.userId}`, false)
        }
        return member
      })
    }
    else {
      await uni.showToast({
        title: resp.msg,
        duration: 2000,
        icon: 'error',
      })
    }
  }
  catch (e) {
    await uni.showToast({
      title: '网络错误',
      duration: 2000,
      icon: 'error',
    })
  }
}, { immediate: true })
</script>

<template>
  <view class="member-container">
    <view v-for="info in data.memberInfos" :key="info.userId" class="user-info-card">
      <view
        v-if="info.avatar && !avatarLoadErrorMap.get(`${info.userId}`)"
        class="user-info-card__avatar user-info-card__avatar--image"
      >
        <image
          :src="info.avatar"
          class="avatar-image"
          mode="aspectFill"
          @error="handleAvatarError(`${info.userId}`)"
        />
      </view>
      <view v-else class="user-info-card__avatar">
        {{ info.nickname.at(0) }}
      </view>
      <view class="user-info-card__details">
        <view class="user-info-card__name">
          {{ info.nickname }}
        </view>
        <view class="user-info-card__stats">
          {{ `阅读${info.readingDays}天，读了${info.readingBooks}本` }}
        </view>
      </view>
      <view class="user-info-card__tags">
        <span v-show="info.role === `teacher`" class="tag tag--teacher">老师</span>
        <span v-show="`${info.userId}` === userStore.userInfo.id" class="tag tag--me">我</span>
      </view>
    </view>
  </view>
</template>

<style scoped lang="scss">
.member-container {
  .user-info-card {
    display: flex;
    align-items: center;
    background-color: #fff;
    border-radius: 10px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    padding: 15px;
    margin-bottom: 15px;
    box-sizing: border-box;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  }

  .user-info-card__avatar {
    flex-shrink: 0;
    width: 48px;
    height: 48px;
    border-radius: 50%;
    background-color: #6a5acd;
    color: #fff;
    font-size: 24px;
    font-weight: bold;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-right: 15px;
    overflow: hidden; // 确保图片超出圆形区域时被裁剪
  }

  // 针对图片头像的样式调整
  .user-info-card__avatar--image {
    background-color: transparent; // 图片头像不需要背景色
  }

  .avatar-image {
    width: 100%;
    height: 100%;
    object-fit: cover; // 确保图片填充整个圆形区域，并裁剪多余部分
  }

  .user-info-card__details {
    flex: 1;
    min-width: 0;
  }

  .user-info-card__name {
    font-size: 16px;
    font-weight: bold;
    color: #333;
    margin-bottom: 4px;
  }

  .user-info-card__stats {
    font-size: 13px;
    color: #666;
  }

  .user-info-card__tags {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-left: 10px;
    flex-shrink: 0;
  }

  .tag {
    font-size: 12px;
    padding: 4px 8px;
    border-radius: 12px;
    font-weight: 500;
    white-space: nowrap;
  }

  .tag--teacher {
    background-color: #e0f2f7;
    color: #007bff;
  }

  .tag--teacher::before {
    content: '📝 ';
    font-size: 10px;
  }

  .tag--me {
    background-color: #e6ffe6;
    color: #28a745;
  }
}
</style>
